
<template>
  <div class="content-wrapper">
    <div
      class="content-container"
      style="overflow-y: scroll; overflow-x: hidden; max-height: 80vh"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="90px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="培训分类" prop="trainClassify">
              <el-select
                v-model.trim="temp.trainClassify"
                placeholder="请选择"
                @change="handleTrainClassifyChange"
              >
                <el-option
                  v-for="item in dataClassify"
                  :key="item.tag"
                  :label="item.value"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="audit" label="申请原因" prop="reason">
              <el-input
                v-model.trim="temp.reason"
                type="text"
                placeholder="请输入申请原因"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="audit" label="审核人">
              <el-tag
                v-if="temp.handleUserId"
                :disable-transitions="false"
                style="margin-right: 10px"
              >
                {{ temp.handleUserId.label }}
              </el-tag>
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(3, '2')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="培训名称" prop="name">
              <el-input v-model.trim="temp.name" placeholder="请输入培训名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="培训内容" prop="content">
              <el-input
                v-model.trim="temp.content"
                type="textarea"
                placeholder="请输入培训内容"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="培训方式" prop="mode">
              <el-select v-model.trim="temp.mode" placeholder="请选择">
                <el-option
                  v-for="item in mode"
                  :key="item.tag"
                  :label="item.value"
                  :value="item.label"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="考核方式" prop="assess">
              <el-select v-model.trim="temp.assess" placeholder="请选择">
                <el-option
                  v-for="item in assessType"
                  :key="item.tag"
                  :label="item.value"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="培训类型" prop="type">
              <el-select v-model.trim="temp.type" placeholder="请选择">
                <el-option
                  v-for="item in dataType"
                  :key="item.tag"
                  :label="item.value"
                  :value="item.label"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="培训形式" prop="trainForm">
              <el-select v-model.trim="temp.trainForm" placeholder="请选择">
                <el-option
                  v-for="item in trainForm"
                  :key="item.tag"
                  :label="item.value"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="培训地点" prop="documentName">
              <el-input v-model.trim="temp.trainSite" style="width: 150px" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="费用类别" prop="expenseCategory">
              <el-select
                v-model.trim="temp.expenseCategory"
                placeholder="请选择"
                @change="changeExpenseCategory"
              >
                <el-option
                  v-for="item in expenseCategory"
                  :key="item.tag"
                  :label="item.value"
                  :value="item.label"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item
              v-if="expenseCategoryFlag"
              label="预计费用总计"
              prop="documentName"
            >
              <!-- <el-input
                v-model.trim="temp.estimatedCost"
                style="width: 150px"
                type="number"
              > -->
               <el-input v-model="temp.estimatedCost" oninput="if(this.value=='0'){this.value='1';}else{this.value=this.value.replace(/[^0-9]/g,'')};" type="number" style="width: 150px" />
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="培训讲师" prop="TeacherNameList">
              <el-tag
                v-if="temp.TeacherNameList.id"
                :disable-transitions="false"
                style="margin-right: 10px"
              >
                {{ temp.TeacherNameList.label }}
              </el-tag>

              <el-button
                v-if="type != 1"
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(3, '1')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有无证书" prop="documentName">
              <el-radio-group v-model="certificateFlag">
                <el-radio :label="true">有</el-radio>
                <el-radio :label="false">无</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col v-if="certificateFlag" :span="8">
            <el-form-item label="证书名称" prop="documentName">
              <el-input
                v-model.trim="temp.certificateName"
                style="width: 150px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="参加部门" prop="BranchNameList">
          <el-tag
            v-for="(tag, index) in temp.BranchNameList"
            :key="index"
            :disable-transitions="false"
            style="margin-right: 10px"
          >
            {{ tag.label }}
          </el-tag>
          <el-button
            size="mini"
            round
            circle
            icon="el-icon-plus"
            @click="openReview(5)"
          />
        </el-form-item>
        <el-form-item label="参加人员" prop="StaffNameList">
          <el-tag
            v-for="(tag, index) in temp.StaffNameList"
            :key="index"
            :disable-transitions="false"
            style="margin-right: 10px"
          >
            {{ tag.label }}
          </el-tag>
          <el-button
            size="mini"
            round
            circle
            icon="el-icon-plus"
            @click="openReview(4)"
          />
        </el-form-item>
        <!-- 选择文件 -->
        <el-row>
          <el-col :span="8">
            <el-form-item
              v-if="SaveDataList"
              label="培训文档"
              prop="SaveDataList"
            >
              <el-tag
                v-for="item in SaveDataList"
                :key="item.value"
                :disable-transitions="false"
                style="margin-right: 10px"
              >
                {{ item.label }}
              </el-tag>
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="SelectFile"
              /> </el-form-item
          ></el-col>
          <el-col :span="14">
            <el-form-item label="培训时间" prop="Time">
              <div class="block">
                <el-date-picker
                  v-model.trim="temp.Time"
                  :picker-options="pickerOptions"
                  type="datetimerange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="getTime"
                />
              </div> </el-form-item
          ></el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="pushSaveData">提交</el-button>
        </el-form-item>
      </el-form>
    </div>

    <SearchPersonnel
      :search-personnel-data="SearchPersonnelData"
      @dataListData="dataListData"
    />
    <SearchUserList
      :search-user-list-data="SearchUserListData"
      @SearchUserList="SearchUserList"
    />
    <SelectGroupList
      :select-group-list-data="SelectGroupListData"
      @UserGroupListData="UserGroupListData"
    />
    <SelectFile
      :select-file-data="SelectFileData"
      @SelectFileDataList="SelectFileDataList"
    />
    <SearchPersonnelType
      :search-personnel-type-data="SearchPersonnelTypeData"
      @dataList="dataList"
    />
  </div>
</template>

<script>
import { getListItem } from '@/api/base/dict.js'
import SearchPersonnel from '@/components/SearchUser/SearchPersonnel.vue'
import SearchUserList from '@/components/SearchUserList/index'
import SelectGroupList from '@/components/SelectGroupList/index.vue'
import SelectFile from '@/views/train/components/SelectFile/index.vue'
import SearchPersonnelType from '@/components/SearchUserType/index.vue'
import { getBranchList } from '@/api/uc/search'
import SelectTheFile from '@/components/SelectTheFile/index.vue'
import { NewTrain } from '@/api/ts/train.js'
import { getTrainByDocumentFlow } from '@/api/xd/documentFlow.js'
import { get, set } from '@/utils/db.js'

export default {
  components: {
    SelectTheFile,
    SearchUserList,
    SelectGroupList,
    SearchPersonnel,
    SelectFile,
    SearchPersonnelType
  },
  data() {
    var checkBranchNameList = (rule, value, callback) => {
      if (
        this.temp.participateGroupId.length === 0 &&
        this.temp.participateUserId.length === 0
      ) {
        callback(new Error('参加部门或人员不可为空'))
      } else {
        callback()
      }
    }
    var checkStaffNameList = (rule, value, callback) => {
      if (
        this.temp.participateGroupId.length === 0 &&
        this.temp.participateUserId.length === 0
      ) {
        callback(new Error('参加部门或人员不可为空'))
      } else {
        callback()
      }
    }
    var checkSaveDataList = (rule, value, callback) => {
      if (!this.SaveDataList || this.SaveDataList.length === 0) {
        callback(new Error('培训文件不可为空'))
      } else {
        callback()
      }
    }
    var checkTeacherNameList = (rule, value, callback) => {
      if (this.temp.TeacherNameList.id === '') {
        callback(new Error('请选择培训讲师'))
      } else {
        callback()
      }
    }
    return {
      title: '',
      dialogReview: false,
      mode: [],
      dataType: [],
      assessType: [],
      assessMode: '',

      rules: {
        name: [{ required: true, message: '请填写培训名称', trigger: 'blur' }],
        content: [
          { required: true, message: '请填写培训内容', trigger: 'blur' }
        ],
        TeacherNameList: [
          {
            validator: checkTeacherNameList,
            required: true,
            trigger: 'blur'
          }
        ],
        BranchNameList: [
          {
            validator: checkBranchNameList,
            required: true,
            trigger: 'change'
          }
        ],
        StaffNameList: [
          {
            validator: checkStaffNameList,
            required: true,
            trigger: 'change'
          }
        ],
        SaveDataList: [
          {
            validator: checkSaveDataList,
            required: true,
            trigger: 'change'
          }
        ],
        handleUserId: [
          { required: true, message: '请选择审核人', trigger: 'blur' }
        ],
        reason: [
          { required: true, message: '请填写申请原因', trigger: 'blur' }
        ],
        mode: [
          { required: true, message: '请选择培训方式', trigger: 'change' }
        ],
        assess: [
          { required: true, message: '请选择考核方式', trigger: 'change' }
        ],
        trainClassify: [
          { required: true, message: '请选择培训分类', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择培训类型', trigger: 'change' }
        ],
        trainForm: [
          { required: true, message: '请选择培训形式', trigger: 'change' }
        ],
        expenseCategory: [
          { required: true, message: '请选择培费用类别', trigger: 'change' }
        ],
        Time: [{ required: true, message: '请选择培训时间', trigger: 'change' }]
      },
      reviewData: [],
      receiveUserGroupList: [],
      reviewNameList: [],
      headList: [],
      category: '',
      TeacherIdList: [],
      SelectFileData: {},
      documentIds: [],
      SelectGroupListData: {},
      SearchPersonnelData: {},
      SearchUserListData: {},
      SearchPersonnelTypeData: {},
      type: '',
      documentFlowId: '',
      audit: true,
      dataClassify: '',
      temp: {
        participateGroupId: [],
        participateUserId: [],
        Time: [],
        TeacherNameList: { id: '' },
        mode: 'self_study',
        assess: 'examination',
        trainClassify: 'common',
        type: 'tech',
        trainForm: 'inside',
        expenseCategory: 'free'
      },
      certificateFlag: false,
      trainClassify: '',
      SaveDataList: [],
      trainForm: [],
      expenseCategory: [],
      expenseCategoryFlag: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  watch: {
    SaveDataList(data) {
      data.forEach((item) => {
        this.documentIds.push(item.value)
      })
      if (data.length > 0) {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate(['SaveDataList'])
        })
      }
    },
    // 培训审核人
    'temp.trainClassify'(data) {
      this.temp.trainClassify = data
      if (data.indexOf('common') !== -1) {
        this.audit = true
      } else {
        this.audit = false
      }
    },
    'temp.participateUserId'(data) {
      if (data.length > 0) {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate(['StaffNameList'])
          this.$refs['dataForm'].clearValidate(['BranchNameList'])
        })
      }
    },
    'temp.participateGroupId'(data) {
      if (data.length > 0) {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate(['StaffNameList'])
          this.$refs['dataForm'].clearValidate(['BranchNameList'])
        })
      }
    },
    'temp.TeacherNameList'(data) {
      if (data.id !== '') {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate(['TeacherNameList'])
        })
      }
    },
    'temp.handleUserId'(data) {
      if (data.length > 0) {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate(['handleUserId'])
        })
      }
    }
  },

  mounted() {
    if (this.$route.query.data) {
      this.getDocumentData(JSON.parse(this.$route.query.data))
    } else {
      if (JSON.parse(get('train_newData'))) {
        this.temp = JSON.parse(get('train_newData'))
        this.temp.name = ''
        this.temp.content = ''
        this.temp.reason = ''
        this.temp.Time = []
        console.log(this.temp.expenseCategory, 'this.temp.expenseCategory')
        if (this.temp.expenseCategory.indexOf('free') !== -1) {
          this.expenseCategoryFlag = false
        } else {
          this.expenseCategoryFlag = true
        }
        this.SaveDataList = this.temp.SaveDataList
        if (this.temp.type.indexOf('train_type_document_train') != 1) {
          this.audit = true
        }
      }

      // this.temp.Time=[]
      // this.temp.Time.push(this.temp.startTime)
      // this.temp.Time.push(this.temp.endTime)
    }
    this.getListItems()
  },
  methods: {
    handleTrainClassifyChange() {
      this.$refs['dataForm'].clearValidate()
    },
    // 获取培训方式
    async getListItems() {
      const { data } = await getListItem({
        dictGroupCodes: [
          'train',
          'train_type',
          'assess_method',
          'train_method',
          'train_form',
          'expense_category'
        ]
      })
      data.forEach((item) => {
        console.log(item)
        // eslint-disable-next-line eqeqeq
        if (item.value.indexOf('培训方式') != -1) {
          this.mode = item.children
        } else if (item.value.indexOf('培训分类') !== -1) {
          this.dataClassify = item.children
        } else if (item.value.indexOf('培训类型') !== -1) {
          this.dataType = item.children
        } else if (item.value.indexOf('考核方式') !== -1) {
          this.assessType = item.children
        } else if (item.value.indexOf('培训形式') !== -1) {
          this.trainForm = item.children
        } else if (item.value.indexOf('费用类别') !== -1) {
          this.expenseCategory = item.children
        }
      })
    },

    // 获取文档培训数据
    async getDocumentData(data) {
      this.documentFlowId = data.documentFlowId
      console.log(data,'shsghsgsggs');
      const newObj = { value: data.documentId, label: data.documentName }
      this.temp.TeacherNameList = {
        label: data.trainerUserName,
        id: data.trainerUserId
      }
      this.SaveDataList.push(newObj)
      this.documentIds.push(newObj.value)
      data.documentFlowId
      this.type = data.type
      // 获取回显部门，人员
      const dataList = await getTrainByDocumentFlow({
        documentFlowId: data.documentFlowId
      })
      console.log(dataList, 'dataList')
      if (dataList.data) {
        if (dataList.data.groupResponses) {
          this.temp.BranchNameList = dataList.data.groupResponses || []
          this.temp.BranchNameList.forEach((item) => {
            this.temp.participateGroupId.push(item.id)
          })
        }
        if (dataList.data.userResponses) {
          this.temp.StaffNameList = dataList.data.userResponses || []
          this.temp.StaffNameList.forEach((item) => {
            this.temp.participateUserId.push(item.id)
          })
        }
      }
      this.audit = true
      this.$forceUpdate()
    },

    // 部门获取
    async getBranchList() {
      this.headList = await getBranchList()
    },

    Review() {
      this.dialogReview = false
    },
    // 获取文件
    openDialog(val) {
      this.getUserGroup()
      if (val) {
        this.dialogUploadDocument = true
        return
      }
      this.dialogDocument = true
    },
    // 点击tree

    // 选择文件
    SelectFile() {
      this.documentIds = []
      this.SelectFileData = {
        deleteDialog: true,
        treeData: this.SaveDataList
      }
    },

    // 子组件传过来的数据
    getSavedata(Savedata) {
      this.SaveDataList = Savedata
    },
    pushSaveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.audit) {
            this.temp.handleUserId = ''
            this.temp.reason = ''
          }
          if (!this.temp.TeacherNameList.id) {
            this.$message.warning('培训讲师不可为空')
            return
          }
          const dataList = {
            content: this.temp.content,
            endTime: this.temp.Time[1],
            mode: this.temp.mode,
            name: this.temp.name,
            startTime: this.temp.Time[0],
            type: this.temp.type,
            participateGroupId: this.temp.participateGroupId,
            participateUserId: this.temp.participateUserId,
            trainerUserId: this.temp.TeacherNameList.id,
            documentIds: Array.from(new Set(this.documentIds)),
            documentFlowId: this.documentFlowId,
            reason: this.temp.reason || '',
            handleUserId: this.temp.handleUserId.id || '',
            trainClassify: this.temp.trainClassify,
            trainSite: this.temp.trainSite,
            assess: this.temp.assess,
            personnelType: '',
            //
            trainForm: this.temp.trainForm,
            expenseCategory: this.temp.expenseCategory,
            estimatedCost: this.temp.estimatedCost || 0,
            certificateName: this.temp.certificateName,
            certificateFlag: this.certificateFlag
          }

          if (this.audit) {
            if (!dataList.handleUserId) {
              this.$message.warning('审核人不可为空')
              return
            }
            if (!dataList.reason) {
              this.$message.warning('申请原因不可为空')
              return
            }
          }
          if (dataList.certificateFlag) {
            if (!dataList.certificateName) {
              this.$message.warning('证书名称不可为空')
              return
            }
          }
          // return
          NewTrain(dataList).then((res) => {
            if (res.code == 1) {
              dataList.TeacherNameList = this.temp.TeacherNameList
              if (this.temp.handleUserId) {
                dataList.handleUserId = this.temp.handleUserId
              }

              if (
                dataList.participateGroupId.length == 0 &&
                dataList.participateUserId.length == 0
              ) {
                this.$message.warning('参加部门或人员不可为空')
                return
              }
              if (dataList.documentIds.length == 0) {
                this.$message.warning('培训文件不可为空')
                return
              }
              dataList.BranchNameList = this.temp.BranchNameList
              dataList.StaffNameList = this.temp.StaffNameList
              dataList.SaveDataList = this.SaveDataList
              dataList.Time = this.temp.Time
              set('train_newData', JSON.stringify(dataList))
              this.$message({
                message: '新建成功',
                type: 'success'
              })
              this.$router.push({
                path: '/train/train_list_start',
                query: { trainClassify: this.temp.trainClassify }
              })
            }
          })
        }
      })
    },
    // 选择部门（多选）
    UserGroupListData(data) {
      this.temp.participateGroupId = []
      this.temp.BranchNameList = data
      data.forEach((item) => {
        this.temp.participateGroupId.push(item.id)
      })
      this.$forceUpdate()
    },
    // 选择人员（多选）
    SearchUserList(data) {
      this.temp.participateUserId = []
      this.temp.StaffNameList = data
      data.forEach((item) => {
        this.temp.participateUserId.push(item.id)
      })
      this.$forceUpdate()
    },
    // 选择人员（单选）
    dataListData(data) {
      if (data.length > 0) {
        if (this.personnelType === '1') {
          this.temp.TeacherNameList = data[0]
        } else if (this.personnelType === '2') {
          this.temp.handleUserId = data[0]
        }
      }
      this.$forceUpdate()
    },
    // 选择文件
    SelectFileDataList(data) {
      this.SaveDataList.splice(1)
      this.SaveDataList = data
      this.SaveDataList = Array.from(new Set(this.SaveDataList))
    },
    openReview(val, type, title) {
      // 0为角色 1为角色（总经理，总监） 3为架构 4为架构多选 5部门多选
      if (val == 3) {
        this.SearchPersonnelData = {
          dialogVisible: true
        }
        this.personnelType = type
      } else if (val == 4) {
        this.SearchUserListData = {
          dialogVisible: true
        }
      } else if (val == 5) {
        this.SelectGroupListData = {
          dialogVisible: true,
          temp: this.temp.BranchNameList
        }
      }
    },
    dataList(val) {
      this.temp.handleUserId = val[0]
      this.$forceUpdate()
    },
    getTime(row) {},
    changeExpenseCategory(data) {
      if (data.indexOf('free') !== -1) {
        this.expenseCategoryFlag = false
      } else {
        this.expenseCategoryFlag = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>
//
.buttonleft {
  margin-left: 85%;
}
.buttonup {
  margin-right: 10px;
  font-size: 12px;
  padding: 10px 20px;
}
.inline-block {
  display: inline-block;
}
.tag {
  margin-left: 10px;
}
.active {
  display: none;
}
.inner-container {
  display: -webkit-flex;
  display: flex;
  flex-direction: row;
}

.left-container {
  width: calc(100% - 300px);
}

.right-container {
  width: 300px;

  .el-timeline {
    .el-timeline-item {
      height: 56px;
      line-height: 56px;

      p {
        height: 16px;
        line-height: 16px;
        font-size: 13px;
      }
    }
  }
}
</style>
